package com.asj.house.service.impl;

import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.json.JSONArray;
import cn.hutool.json.JSONUtil;
import com.asj.house.constant.RedisConstants;
import com.asj.house.entity.*;
import com.asj.house.mapper.HouseRoomIntermediaryMapper;
import com.asj.house.returns.RespCode;
import com.asj.house.returns.RespEntity;
import com.asj.house.service.*;
import com.asj.house.utils.RedisUtil;
import com.asj.house.vo.CheckBoxVO;
import com.asj.house.vo.TreeVO;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.google.common.collect.Lists;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Arrays;
import java.util.List;
import java.util.Objects;
import java.util.stream.Collectors;

/**
 * <p>
 * 房屋中介关系表 服务实现类
 * </p>
 *
 * @author asj
 * @since 2021-03-16
 */
@Service
@Slf4j
public class HouseRoomIntermediaryServiceImpl extends ServiceImpl<HouseRoomIntermediaryMapper, HouseRoomIntermediary> implements HouseRoomIntermediaryService {

    @Autowired
    private HouseRoomService houseRoomService;

    @Autowired
    private HouseIntermediaryService houseIntermediaryService;

    @Autowired
    private HouseRoomDetailService houseRoomDetailService;

    @Autowired
    private HouseRoomResourceService houseRoomResourceService;

    @Autowired
    private RedisUtil redisUtil;

    @Override
    public RespEntity<List<CheckBoxVO>> listCheckBoxVO(Integer roomId) {
        QueryWrapper<HouseIntermediary> queryWrapper = new QueryWrapper<>();
        queryWrapper.lambda().eq(HouseIntermediary::getDeleted, 0);
        List<HouseIntermediary> intermediaryList = houseIntermediaryService.list(queryWrapper);

        if (Objects.isNull(intermediaryList) || CollectionUtil.isEmpty(intermediaryList)) {
           return new RespEntity<>(RespCode.SUCCESS);
        }

        List<CheckBoxVO> checkBoxVOList = Lists.newArrayList();
        for (HouseIntermediary houseIntermediary : intermediaryList) {

            QueryWrapper<HouseRoomIntermediary> intermediaryQueryWrapper = new QueryWrapper<>();
            intermediaryQueryWrapper.lambda().eq(HouseRoomIntermediary::getRoomId, roomId)
                    .eq(HouseRoomIntermediary::getDeleted, 0);
            List<HouseRoomIntermediary> roomIntermediaryList = baseMapper.selectList(intermediaryQueryWrapper);

            List<Integer> intermediaryIdList = Lists.newArrayList();
            if (Objects.nonNull(roomIntermediaryList) && CollectionUtil.isNotEmpty(roomIntermediaryList)) {
                intermediaryIdList = roomIntermediaryList.stream()
                        .map(HouseRoomIntermediary::getIntermediaryId)
                        .collect(Collectors.toList());
            }

            CheckBoxVO checkBoxVO = new CheckBoxVO();
            StringBuffer sb = new StringBuffer();
            sb.append(houseIntermediary.getId());
            sb.append("-");
            sb.append(houseIntermediary.getName());
            checkBoxVO.setTitle(sb.toString());
            checkBoxVO.setId(houseIntermediary.getId());

            if (Objects.nonNull(intermediaryIdList) && CollectionUtil.isNotEmpty(intermediaryIdList)) {
                for (Integer id : intermediaryIdList) {
                    if (houseIntermediary.getId().equals(id)) {
                        checkBoxVO.setChecked(true);
                        break;
                    }
                }
            }

            checkBoxVOList.add(checkBoxVO);
        }

        return new RespEntity<>(RespCode.SUCCESS, checkBoxVOList);
    }

    @Override
    public RespEntity updateIntermediary(String ids, Integer roomId) {
        //ids转数组
        String[] idList = ids.split(",");

        if (Objects.isNull(idList) || CollectionUtil.isEmpty(Arrays.asList(idList))) {
            return new RespEntity(RespCode.PARAMETERS_ERROR);
        }

        //删除原有分配
        deleteIntermediary(roomId);

        //新增分配
        insertIntermediary(idList, roomId);

        return new RespEntity(RespCode.SUCCESS);
    }

    private void insertIntermediary(String[] idList, Integer roomId) {
        for (String id : idList) {
            HouseRoomIntermediary houseRoomIntermediary = new HouseRoomIntermediary();
            houseRoomIntermediary.setIntermediaryId(Integer.parseInt(id));
            houseRoomIntermediary.setRoomId(roomId);
            baseMapper.insert(houseRoomIntermediary);
        }
    }

    private void deleteIntermediary(Integer roomId) {
        QueryWrapper<HouseRoomIntermediary> queryWrapper = new QueryWrapper<>();
        queryWrapper.lambda().eq(HouseRoomIntermediary::getRoomId, roomId)
                .eq(HouseRoomIntermediary::getDeleted, 0);
        baseMapper.delete(queryWrapper);
    }

    @Override
    public RespEntity<List<TreeVO>> listTreeVO() {
        String json = redisUtil.get(RedisConstants.key.TREE);
        if (StringUtils.isNotBlank(json)) {
            //树形数据使用缓存数据
            JSONArray jsonArray = JSONUtil.parseArray(json);
            List<TreeVO> treeVOList = JSONUtil.toList(jsonArray, TreeVO.class);
            return new RespEntity<>(RespCode.SUCCESS, treeVOList);
        }else {
            return createTreeCache();
        }
    }

    /**
     * 创建缓存
     * @return
     */
    private RespEntity<List<TreeVO>> createTreeCache() {
        QueryWrapper<HouseIntermediary> queryWrapper = new QueryWrapper<>();
        queryWrapper.lambda().eq(HouseIntermediary::getDeleted, 0);
        List<HouseIntermediary> houseIntermediaryList = houseIntermediaryService.list(queryWrapper);

        List<TreeVO> treeVOList = Lists.newArrayList();
        for (HouseIntermediary houseIntermediary : houseIntermediaryList) {
            TreeVO treeVO = new TreeVO();
            treeVO.setId(houseIntermediary.getId());
            treeVO.setTitle(getTitle(houseIntermediary));

            QueryWrapper<HouseRoomIntermediary> intermediaryQueryWrapper = new QueryWrapper<>();
            intermediaryQueryWrapper.lambda().eq(HouseRoomIntermediary::getIntermediaryId, houseIntermediary.getId()).
                    eq(HouseRoomIntermediary::getDeleted, 0);

            //子集
            List<HouseRoomIntermediary> intermediaryList = baseMapper.selectList(intermediaryQueryWrapper);
            List<TreeVO> childrenList = Lists.newArrayList();
            for (HouseRoomIntermediary houseRoomIntermediary : intermediaryList) {
                TreeVO tree = new TreeVO();
                tree.setId(houseRoomIntermediary.getId());
                tree.setTitle(getChildrenTitle(houseRoomIntermediary.getRoomId()));
                childrenList.add(tree);
            }

            treeVO.setChildren(childrenList);

            treeVOList.add(treeVO);
        }

        //设置缓存 过期时间一分钟
        redisUtil.set(RedisConstants.key.TREE, JSONUtil.toJsonStr(treeVOList), 60);

        return new RespEntity<>(RespCode.SUCCESS, treeVOList);
    }

    /**
     * 数据组装
     * @param roomId
     * @return
     */
    private String getChildrenTitle(Integer roomId) {
        QueryWrapper<HouseRoomDetail> queryWrapper = new QueryWrapper<>();
        queryWrapper.lambda().eq(HouseRoomDetail::getRoomId, roomId)
                .eq(HouseRoomDetail::getDeleted, 0);
        HouseRoomDetail houseRoomDetail = houseRoomDetailService.getOne(queryWrapper);

        QueryWrapper<HouseRoomResource> resourceQueryWrapper = new QueryWrapper<>();
        resourceQueryWrapper.lambda().eq(HouseRoomResource::getRoomId, roomId)
                .eq(HouseRoomResource::getDeleted, 0);
        HouseRoomResource houseRoomResource = houseRoomResourceService.getOne(resourceQueryWrapper);

        HouseRoom houseRoom = houseRoomService.getById(roomId);
        StringBuffer sb = new StringBuffer();
        sb.append(houseRoom.getId());
        sb.append("-");
        sb.append(houseRoom.getName());
        sb.append("-");
        sb.append(houseRoom.getPrice() + "元/月");
        sb.append("-");
        sb.append(houseRoomDetail.getPayType());
        sb.append("-");
        sb.append(getType(houseRoom.getType()));
        sb.append("-");
        sb.append(houseRoomResource.getHouseArea());
        sb.append("-");
        sb.append(houseRoomResource.getHouseType());
        sb.append("-");
        //校验是否是省份
        if (checkProvince(houseRoomDetail.getProvince())) {
            sb.append(houseRoomDetail.getProvince());
            sb.append("-");
        }
        sb.append(houseRoomDetail.getProvince());
        sb.append("-");
        sb.append(houseRoomDetail.getCity());
        sb.append("-");
        sb.append(houseRoomDetail.getAddress());

        return sb.toString();
    }

    /**
     * 直辖市校验
     * @param province
     * @return
     */
    private boolean checkProvince(String province) {
        boolean flag = true;
        switch (province) {
            case "北京市" : flag = false; break;
            case "天津市" : flag = false; break;
            case "上海市" : flag = false; break;
            case "重庆市" : flag = false;
        }
        return flag;
    }

    /**
     * 获取类型
     * @param type
     * @return
     */
    private String getType(Integer type) {
        String roomType = null;

        switch (type) {
            case 1 : roomType = "复式"; break;
            case 2 : roomType = "别墅"; break;
            case 3 : roomType = "园景房"; break;
            case 4 : roomType = "阁楼"; break;
            case 5 : roomType = "单元式"; break;
            case 6 : roomType = "公寓式";
        }

        return roomType;
    }

    /**
     * 数据封装
     * @param houseIntermediary
     * @return
     */
    private String getTitle(HouseIntermediary houseIntermediary) {
        StringBuffer sb = new StringBuffer();
        sb.append(houseIntermediary.getId());
        sb.append("-");
        sb.append(houseIntermediary.getName());
        sb.append("-");
        sb.append(houseIntermediary.getMobile());
        sb.append("-");
        sb.append(houseIntermediary.getIntegral() + "年");
        sb.append("-");
        sb.append(houseIntermediary.getCountry());
        sb.append(" ");
        sb.append(houseIntermediary.getProvince());
        sb.append(" ");
        sb.append(houseIntermediary.getCity());
        return sb.toString();
    }
}
